import enum_data.FormStatus;
import enum_data.MenuType;
import enum_data.TypeDBRecord;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Vector;

/**
 * Created with IntelliJ IDEA.
 * User: valeriykuchma
 * Date: 21.02.13
 * Time: 21:55
 * To change this template use File | Settings | File Templates.
 */
public class FormMain extends JDialog {
    private JPanel contentPane;
    private JButton btn_Exit;
    private MainTable tbl_Main;
    private JButton btn_Add;
    private JButton btn_Sprav;
    private JList lst_Sprav;
    private JButton btn_Edit;
    private JButton btn_Delete;
    private JButton btn_Reports;
    private JList lst_Reports;

    private int sizeWidth = 800;
    private int sizeHeight = 600;



    private static MenuType currentMenu;
    private static MenuType currentSubMenu;
    JList currentMenuList = null;

    private JPopupMenu popupMnu = new JPopupMenu();

    public FormMain() {
        setContentPane(contentPane);
        setModal(true);
        tbl_Main.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        popupMnu.setFont(new Font("Arial", Font.BOLD, 18));

        //region Инициализация формы
        tbl_Main.setGridColor(Color.black);
        //endregion Инициализация формы

        //region Размещаем окно по центру экрана
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int locationX = (screenSize.width - sizeWidth) / 2;
        int locationY = (screenSize.height - sizeHeight) / 2;
        setBounds(locationX, locationY, sizeWidth, sizeHeight);
        //endregion Размещаем окно по центру экрана

        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onClose();
            }
        });

        createMnuSpravochnik();
        createMnuReports();

        //region Обработка кнопок левого меню (btn_Sprav, btn_Reports)

        btn_Sprav.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (lst_Sprav.isVisible()) {
                    lst_Sprav.setVisible(false);
                }
                else {
                    resetLeftMenu();
                    lst_Sprav.setVisible(true);
                    currentMenu = MenuType.SPRAVOCHNIK;
                    currentMenuList = lst_Sprav;

                }
            }
        });

        btn_Reports.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (lst_Reports.isVisible()) {
                    lst_Reports.setVisible(false);
                }
                else {
                    resetLeftMenu();
                    lst_Reports.setVisible(true);
                    currentMenu = MenuType.REPORT;
                    currentMenuList = lst_Reports;
                }
            }
        });

        //endregion Обработка кнопок левого меню (btn_Sprav, btn_Reports)

        btn_Exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                dispose();
            }
        });

        tbl_Main.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                tblSelectControl();

                if (mouseEvent.getClickCount() == 2){
                        tbl_Main.openAdditionalForm(currentSubMenu, FormStatus.EDIT);
                        try {
                            writeMainTable();
                        } catch (SQLException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        tblSelectControl();
                }
            }
        });

        btn_Edit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                tbl_Main.openAdditionalForm(currentSubMenu, FormStatus.EDIT);
                try {
                    writeMainTable();
                } catch (SQLException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
        btn_Add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                tbl_Main.openAdditionalForm(currentSubMenu, FormStatus.NEW);
                try {
                    writeMainTable();
                } catch (SQLException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
        btn_Delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                String dbName = null;

                switch (currentSubMenu){
                    case SPRAVOCHNIK_USERS:
                        dbName = "tradexpert.user";
                        break;
                    case SPRAVOCHNIK_PRIVILEGIES:
                        dbName = "tradexpert.privilegie";
                        break;
                }
                String userID = (String)tbl_Main.getValueAt(tbl_Main.getSelectedRow(), 0);
                String queryUpdate = "UPDATE " + dbName + " SET state='" + TypeDBRecord.RECORD_DELETE + "' WHERE id='" + userID + "'";

                try {
                    TEDatabase.updateDB(queryUpdate);
                    writeMainTable();
                } catch (SQLException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
    }

    public static MenuType getCurrentMenu() {
        return currentMenu;
    }

    public static MenuType getCurrentSubMenu() {
        return currentSubMenu;
    }

    private void tblSelectControl(){
        //Если выделена строка таблицы - активировать кнопки Добавить, Редактировать, Вставить
        if (tbl_Main.getSelectedRow() != -1){
            btn_Edit.setEnabled(true);
            btn_Delete.setEnabled(true);
        } else {
            btn_Edit.setEnabled(false);
            btn_Delete.setEnabled(false);
        }
    }



    private void writeMainTable() throws SQLException {
        ResultSet tableData = null;
        String[] colomnName=null;
//        JOptionPane.showMessageDialog(null, "writeMainTable");
        switch (currentSubMenu) {
            case SPRAVOCHNIK_USERS:   //SUB_MENU_USERS
                tableData = TEDatabase.execQuery("SELECT user.id, user.state, user.login, user.fio, privilegie.privilegie_name " +
                        "FROM user INNER JOIN privilegie ON user.privilegie = privilegie.id WHERE user.state < 1");
                colomnName = new String[]{"id", "state", "Логин", "ФИО", "Должность"};
                btn_Add.setEnabled(true);
                break;
            case SPRAVOCHNIK_PRIVILEGIES: //SUB_MENU_PRIVOLEGIES
                tableData = TEDatabase.execQuery("select privilegie.id, privilegie.state, privilegie.privilegie_name from privilegie WHERE privilegie.state < 1");
                colomnName = new String[]{"id", "state", "Должность"};
                btn_Add.setEnabled(true);
                break;
        }

        int numColumns = tableData.getMetaData().getColumnCount();
        Vector column = new Vector();
        Vector data = new Vector();
        Collections.addAll(column, colomnName); // Заполняем название колонок

        while (tableData.next()) {
            Vector row = new Vector();
            for (int i = 1; i <= numColumns; i++) {
                row.add(tableData.getString(i));
            }
            data.add(row);
        }


        tbl_Main.setModel(new javax.swing.table.DefaultTableModel(data, column));

        //скрываем колонку id
        tbl_Main.getColumnModel().getColumn(0).setMaxWidth(0);
        tbl_Main.getColumnModel().getColumn(0).setMinWidth(0);
        tbl_Main.getColumnModel().getColumn(0).setPreferredWidth(0);
        //скрываем колонку state
        tbl_Main.getColumnModel().getColumn(1).setMaxWidth(0);
        tbl_Main.getColumnModel().getColumn(1).setMinWidth(0);
        tbl_Main.getColumnModel().getColumn(1).setPreferredWidth(0);
    }

    private void resetLeftMenu (){
        lst_Reports.setVisible(false);
        lst_Sprav.setVisible(false);
        currentMenuList = null;
    }

    class PopupMenuL implements ActionListener {
        public void actionPerformed(ActionEvent e) {
//            JOptionPane.showMessageDialog(null, "Выбрано - " + e.getActionCommand());
            String selectSubMenu = e.getActionCommand();
            try {
            if (selectSubMenu.equals("Пользователи")) {
                currentSubMenu = MenuType.SPRAVOCHNIK_USERS;
                    writeMainTable();
            }
//            Права доступа
            if (selectSubMenu.equals("Должности")) {
                currentSubMenu = MenuType.SPRAVOCHNIK_PRIVILEGIES;
                    writeMainTable();
            }
            } catch (SQLException e1) {
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
        }
    }

    class MouseL extends MouseAdapter {

        public void mouseClicked(MouseEvent me) {
            if (SwingUtilities.isLeftMouseButton(me)) {
                int index = currentMenuList.locationToIndex(me.getPoint());
                if (index != -1) {
                    currentMenuList.setSelectedIndex(index);

                        if (writePopupMenu(index)) {
                            popupMnu.show(me.getComponent(), me.getX()+10, me.getY()+10);
                        }

                }

            }
        }

    }

    private boolean writePopupMenu(int index) {

        if (currentMenu == MenuType.REPORT)
            return false;

        String[] data = null;
        popupMnu.removeAll();

        switch (index){
            case 0:
                data = new String[]{"Пользователи", "Должности"};
                break;
            case 1:
                data = new String[]{"Товар", "Производитель"};
                break;
        }

        popupMnu.addSeparator();
        for (int i = 0; i < data.length; i++) {
            JMenuItem item = new JMenuItem(data[i]);
            item.addActionListener(new PopupMenuL());
            popupMnu.add(item);
            popupMnu.addSeparator();
        }
        lst_Sprav.add(popupMnu);

        return true;
    }

    class ListSelectionL implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent event) {
        }
    }

    private void createMnuSpravochnik(){
        String[] data = {"Пользователи", "Товар"};
        lst_Sprav.setListData(data);
        lst_Sprav.setFixedCellHeight(30);
        lst_Sprav.setVisible(false);

        lst_Sprav.addMouseListener(new MouseL());
    }

    private void createMnuReports(){
        String[] data = {"Товарные", "Бухгалтерские"};
        lst_Reports.setListData(data);
        lst_Reports.setFixedCellHeight(30);
        lst_Reports.setVisible(false);

        lst_Reports.addMouseListener(new MouseL());
    }

    private void onClose() {
        System.exit(0);
    }





}
